#include "breakpoints.hpp"
#include "ui_breakpoints.h"

Breakpoints::Breakpoints(QWidget *parent) :
    QDockWidget(parent),
    ui(new Ui::Breakpoints)
{
    ui->setupUi(this);
}


Breakpoints::~Breakpoints()
{
    delete ui;
}


void Breakpoints::changeEvent(QEvent *e)
{
    QDockWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}


void Breakpoints::onBreakpointToggled(int line, bool add, QString asmCode, QString anchor)
{
    if (add)
    {
	QString address = QString::number(line, 10).toUpper();
	while (address.size() < 5)
	    address.prepend("0");

	Breakpoint newBreakpoint;
	newBreakpoint.line = new QTableWidgetItem(address);
	newBreakpoint.code = new QTableWidgetItem(asmCode);
	newBreakpoint.anchor = anchor;

	int row = ui->tbl_breakpoints->rowCount();
	ui->tbl_breakpoints->setRowCount(row + 1);
	ui->tbl_breakpoints->setItem(row, 0, newBreakpoint.line);
	ui->tbl_breakpoints->setItem(row, 1, newBreakpoint.code);

	this->breakpointMap.insert(line, newBreakpoint);
    } else {
	Breakpoint current = this->breakpointMap.find(line).value();
	int row = ui->tbl_breakpoints->row(current.code);
	delete current.code;
	delete current.line;
	ui->tbl_breakpoints->removeRow(row);
	this->breakpointMap.remove(line);
    }
}


void Breakpoints::on_tbl_breakpoints_cellDoubleClicked(int row, int column)
{
    QTableWidgetItem *current = ui->tbl_breakpoints->item(row, 0);

    QMapIterator<int, Breakpoint> it(this->breakpointMap);

    while (it.hasNext())
    {
	it.next();

	if (it.value().line == current)
	{
	    emit jumpToBreakpoint(it.value().anchor);
	    break;
	}
    }
}


void Breakpoints::reset()
{
    QList<int> keys = this->breakpointMap.keys();

    while (!keys.isEmpty())
    {
	delete this->breakpointMap.find(keys.first()).value().code;
	delete this->breakpointMap.find(keys.first()).value().line;
	this->breakpointMap.remove(keys.takeFirst());
    }

    ui->tbl_breakpoints->clearContents();
}
